//
//  MyTextView.m
//  79环信
//
//  Created by 刘恒槟 on 15/8/4.
//  Copyright (c) 2015年 刘恒槟. All rights reserved.
//

#import "MyTextView.h"
#import "FaceKeyBoard.h"
#import "FunctionKeyBoard.h"
@interface MyTextView ()<FaceKeyBoardDataSource,FaceKeyBoardDelegate,FunCtionDelegate>

@property(nonatomic,strong)NSArray * faces;

@property(nonatomic,strong)NSMutableArray * faceImageData;

@property (nonatomic ,strong) FaceKeyBoard * faceKB;
@property (nonatomic ,strong) FunctionKeyBoard * funcKB;

@end

@implementation MyTextView

-(instancetype)initWithFrame:(CGRect)frame{
    
    self =[super initWithFrame:frame];
    
    if (self) {
                
        [self faceItem];
        
        [[NSNotificationCenter defaultCenter]addObserver:self selector:@selector(changeKeyBoard) name:@"ChatViewConTrollerWillDisMiss" object:nil];
    }

    return self;
}

-(void)changeKeyBoard{
    
    [self changeKeyBoardWithKeyBoardType:KeyBoardTypeWithSystemKeyBoard];
    
    [self resignFirstResponder];
}

-(void)faceItem{
    
    //找到本地emoticons.plist文件
    NSString * path = [[NSBundle mainBundle] pathForResource:@"emoticons" ofType:@"plist"];
    //将文件中的内容读取出来存入数组中
    self.faces = [NSArray arrayWithContentsOfFile:path];
    //存储图片二进制数据的数组
    self.faceImageData = [NSMutableArray arrayWithCapacity:self.faces.count];
    
    //将图片名字对应的图片转为二进制数据存入数组
    for (int i = 0; i<self.faces.count; i++)
    {
        NSDictionary * dic = self.faces[i];
        NSString * imageName = dic[@"chs"];
        UIImage * image = [UIImage imageNamed:dic[@"png"]];
        
        NSData * imageData = UIImagePNGRepresentation(image);
        
        NSDictionary * dic1 = @{@"name":imageName,@"data":imageData};
        
        [self.faceImageData addObject:dic1];
        
    }
    
    CGFloat Width = [UIScreen mainScreen].bounds.size.width;
    
    CGFloat itemWidth = Width/8;
    
    self.faceKB = [[FaceKeyBoard alloc]initWithFrame:CGRectMake(0, 0, Width, 4 * itemWidth)];
    
    self.faceKB.dataSource = self;
    self.faceKB.delegate = self;
    
    CGFloat funcItemWidth = Width/3;
    
    self.funcKB = [[FunctionKeyBoard alloc]initWithFrame:CGRectMake(0, 0, Width, funcItemWidth * 2)];
    
    self.funcKB.delegate = self;
    

}

-(void)functionKeyBoard:(FunctionKeyBoard *)func DidTapButtonIndex:(NSInteger)buttonIndex{
    
    if ([self.MyTextViewdelegate respondsToSelector:@selector(TextView:DidTapFunctionItem:)]){
    
        [self.MyTextViewdelegate TextView:self DidTapFunctionItem:buttonIndex];
    }
}

-(void)FaceKeyBoard:(FaceKeyBoard *)faceKb didTapFaceItemIndex:(NSInteger)buttonIndex{
    
    //根据button的tag值取出对应的图片
    NSDictionary * dic = self.faces[buttonIndex];
    NSString * name = dic[@"png"];
    UIImage * image = [UIImage imageNamed:name];
    
    //初始化一个可变的属性字符串
    NSMutableAttributedString * attString = [[NSMutableAttributedString alloc]initWithAttributedString:self.attributedText];
    
    //iOS7新增的类，作为文本的附件，可以放文件，可以放数据，以 NSAttachmentAttributeName这个key放入NSAttributedString里面，在图文混排这里，我们将放入image
    NSTextAttachment * attachment = [[NSTextAttachment alloc]init];
    attachment.image = image;
    //将附文本放入属性字符串
    NSAttributedString * imageString = [NSAttributedString attributedStringWithAttachment:attachment];
    [attString appendAttributedString:imageString];
    //将属性字符串显示在textview上
    self.attributedText = attString;
    
    
}

-(NSInteger)numberOfFaceItemInFaceKeyBoard:(FaceKeyBoard *)faceKb{
    
    return self.faces.count;
}

-(UIImage *)FaceKeyboard:(FaceKeyBoard *)faceKb FaceItemImageAtIndex:(NSInteger)index{
    
    NSDictionary * dic = self.faces[index];
    NSString * name = dic[@"png"];
    UIImage * image = [UIImage imageNamed:name];
    return image;
}

//传入一个属性字符串，返回普通字符串
-(NSString *)imageText
{
    NSMutableAttributedString * attString = [[NSMutableAttributedString alloc]initWithAttributedString:self.attributedText];
    
    NSMutableArray * faceItems = [NSMutableArray array];
    //枚举指定范围内的属性信息和range信息
    [attString enumerateAttributesInRange:NSMakeRange(0, attString.length) options:(NSAttributedStringEnumerationReverse) usingBlock:^(NSDictionary *attrs, NSRange range, BOOL *stop) {
        //取出附文本
        NSTextAttachment * attachment = attrs[@"NSAttachment"];
        //找到附文本的图片的位置
        if (attachment)
        {
            UIImage * image = attachment.image;
            NSValue * position = [NSValue valueWithRange:range];
            //将图片及图片的位置放入一个字典
            NSDictionary * dic = @{@"image":image,@"range":position};
            [faceItems addObject:dic];
            
        }
    }];
    
    //遍历数组，用[XX]将图片替换
    for (int i = 0; i<faceItems.count; i++)
    {
        NSDictionary * dic = faceItems[i];
        UIImage * image = dic[@"image"];
        NSRange range = [dic[@"range"] rangeValue];
        //传入图片，返回图片的名字
        NSString * imageName = [self nameWithImage:image];
        //在图片的位置用名字将图片替换
        [attString replaceCharactersInRange:range withString:imageName];
        
    }
    
    return attString.string;
}

//传入一张图片，返回图片的名字
-(NSString *)nameWithImage:(UIImage *)image
{
    NSData * d1 = UIImagePNGRepresentation(image);
    
    for (int i =0; i<self.faceImageData.count; i++)
    {
        NSDictionary * dic = self.faceImageData[i];
        
        NSData * data = dic[@"data"];
        
        if ([d1 isEqualToData:data])
        {
            NSString * name = dic[@"name"];
            return name;
        }
    }
    
    return nil;
}

-(void)changeKeyBoardWithKeyBoardType:(KeyBoardType)type{
    
    switch (type) {
        case KeyBoardTypeWithSystemKeyBoard:
        {
            NSLog(@"显示系统键盘");
            
            self.inputView = nil;
            
        }
            break;
        case KeyBoardTypeWithFaceKeyBoard:
        {
            NSLog(@"显示表情键盘");
            
            self.inputView = self.faceKB;
            
        }
            break;
        case KeyBoardTypeWithFunctionKeyBoard:
        {
            NSLog(@"显示功能键盘");
            self.inputView = self.funcKB;
        }
            break;

            
        default:
            break;
    }
    
    if (self.isFirstResponder)
    {
        [self reloadInputViews];
    }
    else
    {
        [self becomeFirstResponder];
    }
}

@end
